<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>智能生成试卷</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回试卷列表</el-button>
      </div>
      
      <!-- 生成试卷表单 -->
      <el-form ref="generateForm" :model="generateForm" :rules="rules" label-width="100px" v-loading="loading">
        <el-form-item label="试卷标题" prop="title">
          <el-input v-model="generateForm.title" placeholder="请输入试卷标题"></el-input>
        </el-form-item>
        
        <el-form-item label="学科" prop="subjectId">
          <el-select v-model="generateForm.subjectId" placeholder="请选择学科" filterable>
            <el-option
              v-for="item in subjectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="教育阶段" prop="educationLevel">
          <el-select v-model="generateForm.educationLevel" placeholder="请选择教育阶段" @change="handleEducationLevelChange">
            <el-option label="小学" :value="1"></el-option>
            <el-option label="初中" :value="2"></el-option>
            <el-option label="高中" :value="3"></el-option>
            <el-option label="大学" :value="4"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="考试时长" prop="duration">
          <el-input-number v-model="generateForm.duration" :min="10" :max="240" :step="5" step-strictly></el-input-number>
          <span class="unit">分钟</span>
        </el-form-item>
        
        <el-form-item label="总分" prop="totalScore">
          <el-input-number v-model="generateForm.totalScore" :min="10" :max="1000" :step="10" step-strictly></el-input-number>
          <span class="unit">分</span>
        </el-form-item>
        
        <el-form-item label="试卷难度" prop="difficulty">
          <el-slider v-model="generateForm.difficulty" :min="1" :max="5" :step="1" show-stops>
            <template slot="default">
              <span class="difficulty-label">简单</span>
              <span class="difficulty-label" style="left: 25%;">较简单</span>
              <span class="difficulty-label" style="left: 50%;">中等</span>
              <span class="difficulty-label" style="left: 75%;">较难</span>
              <span class="difficulty-label" style="left: 100%;">困难</span>
            </template>
          </el-slider>
        </el-form-item>
        
        <el-form-item label="内容关键词" prop="keywords">
          <el-input v-model="generateForm.keywords" placeholder="请输入内容关键词，例如：光合作用,植物呼吸"></el-input>
        </el-form-item>
        
        <el-form-item label="题型配置" prop="questionTypes">
          <div class="question-types-container">
            <div v-for="(item, index) in questionTypeOptions" :key="index" class="question-type-item">
              <el-checkbox v-model="selectedQuestionTypes[index]">{{ item.label }}</el-checkbox>
              <el-input-number 
                v-if="selectedQuestionTypes[index]" 
                v-model="generateForm.questionTypeConfigs[index].count" 
                :min="1" 
                :max="50" 
                :step="1" 
                size="mini"
                @change="updateTotalCount">
              </el-input-number>
              <span v-if="selectedQuestionTypes[index]" class="unit">题</span>
            </div>
          </div>
          <div class="question-count">
            <span>总题数: {{ totalQuestionCount }}</span>
          </div>
        </el-form-item>
        
        <el-form-item label="AI提示词">
          <el-input
            type="textarea"
            v-model="generateForm.prompt"
            :rows="4"
            placeholder="请输入额外的指导提示，例如：注重基础知识，包含一定的思维挑战题，难度适中">
          </el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">生成试卷</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 生成结果弹窗 -->
    <el-dialog 
      title="试卷生成结果" 
      :visible.sync="resultDialogVisible"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="generationComplete">
      <div class="generation-result">
        <div v-if="!generationComplete" class="generating">
          <el-progress type="circle" :percentage="generationProgress" :status="generationProgress >= 100 ? 'success' : ''"></el-progress>
          <p class="status-text">{{ generationStatusText }}</p>
        </div>
        <div v-else class="generation-complete">
          <i class="el-icon-success success-icon"></i>
          <h3>试卷生成成功</h3>
          <p>试卷标题：{{ generateForm.title }}</p>
          <p>共 {{ totalQuestionCount }} 道题目，总分 {{ generateForm.totalScore }} 分</p>
          <div class="action-buttons">
            <el-button type="primary" @click="viewPaper">查看试卷</el-button>
            <el-button @click="closeResultDialog">继续创建</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { generateAIPaper, getAISupportedSubjects } from '@/api/paper';

export default {
  name: 'AIPaperGenerate',
  data() {
    return {
      // 生成表单
      generateForm: {
        title: '',
        subjectId: undefined,
        educationLevel: undefined,
        duration: 90, // 默认90分钟
        totalScore: 100, // 默认100分
        difficulty: 3, // 默认中等难度 (1-5)
        keywords: '',
        prompt: '',
        questionTypeConfigs: [
          { type: 1, count: 10 }, // 单选题
          { type: 2, count: 5 }, // 多选题
          { type: 3, count: 5 }, // 判断题
          { type: 4, count: 3 }, // 填空题
          { type: 5, count: 2 } // 简答题
        ]
      },
      // 表单验证规则
      rules: {
        title: [
          { required: true, message: '请输入试卷标题', trigger: 'blur' }
        ],
        subjectId: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        educationLevel: [
          { required: true, message: '请选择教育阶段', trigger: 'change' }
        ],
        duration: [
          { required: true, message: '请输入考试时长', trigger: 'blur' }
        ],
        totalScore: [
          { required: true, message: '请输入总分', trigger: 'blur' }
        ]
      },
      // 学科选项
      subjectOptions: [],
      // 题型选项
      questionTypeOptions: [
        { label: '单选题', value: 1 },
        { label: '多选题', value: 2 },
        { label: '判断题', value: 3 },
        { label: '填空题', value: 4 },
        { label: '简答题', value: 5 }
      ],
      // 选中的题型
      selectedQuestionTypes: [true, true, true, true, true],
      // 加载状态
      loading: false,
      // 提交状态
      submitLoading: false,
      // 结果对话框
      resultDialogVisible: false,
      // 生成是否完成
      generationComplete: false,
      // 生成进度
      generationProgress: 0,
      // 生成状态文本
      generationStatusText: '正在准备生成...',
      // 生成结果
      generationResult: null,
      // 定时器id
      progressTimer: null
    };
  },
  computed: {
    // 总题数
    totalQuestionCount() {
      return this.generateForm.questionTypeConfigs.reduce((sum, config, index) => {
        return sum + (this.selectedQuestionTypes[index] ? config.count : 0);
      }, 0);
    }
  },
  created() {
    this.getSubjects();
  },
  beforeDestroy() {
    if (this.progressTimer) {
      clearInterval(this.progressTimer);
    }
  },
  methods: {
    // 获取学科列表
    getSubjects() {
      this.loading = true;
      getAISupportedSubjects().then(response => {
        const subjects = response.data || [];
        
        // 初始化时显示所有学科或根据已选教育阶段过滤
        if (this.generateForm.educationLevel) {
          this.filterSubjectsByLevel(this.generateForm.educationLevel);
        } else {
          this.subjectOptions = subjects.map(subject => ({
            value: subject.id,
            label: subject.name
          }));
        }
        
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    
    // 根据教育阶段筛选学科
    filterSubjectsByLevel(level) {
      if (!level) {
        this.subjectOptions = this.allSubjects.map(subject => ({
          value: subject.id,
          label: subject.name
        }));
        return;
      }

      const filteredSubjects = this.allSubjects.filter(subject => subject.level === level);
      this.subjectOptions = filteredSubjects.map(subject => ({
        value: subject.id,
        label: subject.name
      }));
      
      // 如果当前选中的学科不在筛选结果中，清空选择
      if (this.generateForm.subjectId) {
        const exists = filteredSubjects.some(subject => subject.id === this.generateForm.subjectId);
        if (!exists) {
          this.generateForm.subjectId = undefined;
        }
      }
    },
    
    // 更新总题数
    updateTotalCount() {
      // 自动校验
      this.$nextTick(() => {
        this.validateQuestionTypes();
      });
    },
    
    // 校验题型配置
    validateQuestionTypes() {
      // 至少选择一种题型
      const hasSelected = this.selectedQuestionTypes.some(selected => selected);
      if (!hasSelected) {
        this.$message.warning('请至少选择一种题型');
        // 默认选中第一个
        this.selectedQuestionTypes[0] = true;
      }
    },
    
    // 提交表单
    submitForm() {
      this.$refs.generateForm.validate(valid => {
        if (valid) {
          // 校验题型
          this.validateQuestionTypes();
          if (this.totalQuestionCount === 0) {
            this.$message.warning('请至少添加一道题目');
            return;
          }
          
          // 构建请求数据
          const requestData = {
            ...this.generateForm,
            questionTypes: this.generateForm.questionTypeConfigs
              .filter((_, index) => this.selectedQuestionTypes[index])
              .map(config => ({ 
                type: config.type, 
                count: config.count
              }))
          };
          
          this.submitLoading = true;
          this.showGenerationDialog();
          
          // 调用API生成试卷
          generateAIPaper(requestData).then(response => {
            this.submitLoading = false;
            this.generationComplete = true;
            this.generationProgress = 100;
            this.generationResult = response.data;
            console.log('生成的试卷ID:', this.generationResult ? this.generationResult.id : 'undefined');
            this.generationStatusText = '试卷生成成功！';
            
            // 清除进度定时器
            if (this.progressTimer) {
              clearInterval(this.progressTimer);
            }
          }).catch(error => {
            this.submitLoading = false;
            this.generationComplete = true;
            this.generationStatusText = '试卷生成失败：' + (error.message || '未知错误');
            
            // 清除进度定时器
            if (this.progressTimer) {
              clearInterval(this.progressTimer);
            }
          });
        }
      });
    },
    
    // 显示生成对话框
    showGenerationDialog() {
      this.resultDialogVisible = true;
      this.generationComplete = false;
      this.generationProgress = 0;
      this.generationStatusText = '正在准备生成...';
      
      // 模拟进度
      this.progressTimer = setInterval(() => {
        if (this.generationProgress < 95) {
          const increment = Math.random() * 5 + 1;
          this.generationProgress = Math.min(95, this.generationProgress + increment);
          
          // 更新状态文本
          if (this.generationProgress < 20) {
            this.generationStatusText = '正在分析学科知识点...';
          } else if (this.generationProgress < 40) {
            this.generationStatusText = '正在生成题目...';
          } else if (this.generationProgress < 70) {
            this.generationStatusText = '正在设计答案与解析...';
          } else {
            this.generationStatusText = '正在组装试卷...';
          }
        }
      }, 800);
    },
    
    // 关闭结果对话框
    closeResultDialog() {
      this.resultDialogVisible = false;
    },
    
    // 查看试卷
    viewPaper() {
      const paperId = this.generationResult ? this.generationResult.id : null;
      console.log('跳转到试卷详情，ID:', paperId);
      if (paperId) {
        this.$router.push(`/paper/detail/${paperId}`);
      } else {
        this.$message.error('试卷ID不存在，无法查看');
      }
    },
    
    // 重置表单
    resetForm() {
      this.$refs.generateForm.resetFields();
      this.generateForm.duration = 90;
      this.generateForm.totalScore = 100;
      this.generateForm.difficulty = 3;
      this.generateForm.questionTypeConfigs = [
        { type: 1, count: 10 }, // 单选题
        { type: 2, count: 5 }, // 多选题
        { type: 3, count: 5 }, // 判断题
        { type: 4, count: 3 }, // 填空题
        { type: 5, count: 2 } // 简答题
      ];
      this.selectedQuestionTypes = [true, true, true, true, true];
    },
    
    // 返回试卷列表
    goBack() {
      this.$router.push('/papers');
    },

    // 教育阶段变化时的处理逻辑
    handleEducationLevelChange(level) {
      this.filterSubjectsByLevel(level);
    }
  }
};
</script>

<style scoped>
.unit {
  margin-left: 10px;
  color: #606266;
}

.question-types-container {
  display: flex;
  flex-wrap: wrap;
}

.question-type-item {
  margin-right: 20px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.question-count {
  margin-top: 10px;
  color: #409EFF;
  font-weight: bold;
}

.difficulty-label {
  position: absolute;
  transform: translateX(-50%);
  font-size: 12px;
  color: #606266;
  top: 20px;
  line-height: 1;
}

.generating {
  text-align: center;
  padding: 20px 0;
}

.status-text {
  margin-top: 15px;
  color: #606266;
}

.generation-complete {
  text-align: center;
  padding: 20px 0;
}

.success-icon {
  font-size: 48px;
  color: #67C23A;
}

.action-buttons {
  margin-top: 20px;
}

.el-slider {
  width: 90%;
  margin-left: 5%;
  padding-bottom: 30px;
}
</style> 